﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace SMS.Stocks
{
    public partial class SearchStock : System.Web.UI.Page
    {
        public List<SMS.DAL.Stock> StocksFound
        {
            set
            {
                ViewState["StockFound"] = value;
            }

            get
            {
                return (List<SMS.DAL.Stock>)ViewState["StockFound"];
            }
        }
        SMS.Business.Stocks.StocksBusiness StckBuss;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["CurrentUser"] == null)
                Response.Redirect(@"~\Account\Login.aspx");
            StckBuss = new Business.Stocks.StocksBusiness();

        }

        protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            Response.Redirect("NewStock.aspx?StockID=" + SMS.Helper.QueryEncoder.Encrypt( GridView1.SelectedDataKey.Value.ToString()));
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            StocksFound = StckBuss.Search(new DAL.Providers.StockSearchCriteria() { Name = txtName.Text, type = drpStockType.SelectedIndex == 0 ? (int?)null : (drpStockType.SelectedIndex - 1) });
            this.GridView1.DataSource = StocksFound;           
            this.DataBind();
        }

        protected void drpStockType_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            StckBuss.Delete((int)(e.Keys["ID"]));
            StocksFound.Remove(StocksFound.Where(c => c.ID == (int)(e.Keys["ID"])).SingleOrDefault());
            this.GridView1.DataSource = StocksFound;
            this.DataBind();
        }

        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                if (((SMS.DAL.Stock)(e.Row.DataItem)).Type == 0)
                    e.Row.Cells[2].Text = "محل";
                else
                    e.Row.Cells[2].Text = "مخزن";
            }
        }

        protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            this.GridView1.PageIndex = e.NewPageIndex;
            this.GridView1.DataSource = StocksFound;
            this.DataBind();
        }
    }
}